package io.renren.modules.clearing.service.impl;

import cn.com.taiji.common.manager.net.http.binclient.ApiRequestException;
import cn.com.taiji.sdk.comm.LwClientHelper;
import cn.com.taiji.sdk.model.comm.protocol.cdts.passTransaction.ETCDisputeDetailDownloadRequest;
import cn.com.taiji.sdk.model.comm.protocol.cdts.passTransaction.ETCDisputeDetailTransaction;
import io.renren.common.utils.*;
import io.renren.modules.basedata.entity.XJException;
import io.renren.modules.clearing.dao.*;
import io.renren.modules.clearing.entity.DataExchangeList;
import io.renren.modules.clearing.entity.ETCAccountTradeDown;
import io.renren.modules.clearing.entity.ETCDisputeDetail;
import io.renren.modules.clearing.entity.ETCDisputeDetailMessageList;
import io.renren.modules.clearing.service.ETCDisputeDetailDownloadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class ETCDisputeDetailDownloadServiceImpl implements ETCDisputeDetailDownloadService {
    private Logger log = LoggerFactory.getLogger(getClass());
    @Autowired
    ETCAccountTradeDownDao etcAccountTradeDownDao;
    @Autowired
    ConfigParaDicDao configParaDicDao;
    @Autowired
    DataExchangeListDao dataExchangeListDao;
    @Autowired
    DownVersionDicDao downVersionDicDao;
    @Autowired
    ZFKExitWasteDao zfkExitWasteDao;
    @Autowired
    DownErrorVersionDao downErrorVersionDao;

    @Override
    public String[] ETCDisputeDetailDownload(String sender) throws Exception {

        // TODO Auto-generated method stub
        String msg="";
        String version=null;
        String[] versions=null;
        log.info("开始检查控制参数");
        //检查控制参数是否下载 tbl_configparadic
        int control = configParaDicDao.checkContolParam(Constants.CONTROL_ETCAUDOWN_PARAM);
        //int control=(Integer) sqlMapClient.queryForObject("Base_ORACLE.checkContolParam",Constants.CONTROL_ETCDDDOWN_PARAM);
        if(control==1){
            //获取要需下载的版本号
            version = downVersionDicDao.getVersion(Constants.DOWNLOAD_TYPE_ETCACCOUNTTRADEDOWNLOAD);
            //version=(String) sqlMapClient.queryForObject("Base_ORACLE.getVersion",sender== Config.issuerId?Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD_ISSUEID:Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD);
            if(version!=null ){
                //判断有多少版本号要处理
                versions= TypeTransUtil.checkVersion(version, Constants.DOWNLOAD_FILE_1H);

            }else{
                msg="版本字典表无该参数配置";
                log.info(msg);
            }
        }else{
            msg="接口暂停，任务退出";
            log.info(msg);
        }
        return versions;

    }
    /**
     * 根据版本号请求记账交易下载
     * @param version
     * @return
     * @throws Exception
     */
    @Override
    public boolean DownloadFile(String version, String sender, int type) throws Exception {


        boolean flag=false;
        ETCDisputeDetailDownloadRequest request= new ETCDisputeDetailDownloadRequest();

        request.setVersion(version);
        request.setReqSender(sender);
        log.info(request.toJson());
        log.info("开始执行版本:"+version);
        String path=";文件路径:";
        try {
            File file = LwClientHelper.downLoad(request, Constants.DOWNLOAD_PATH_ETCDISPUTE);
            System.out.println("ETC争议处理结果交易下载成功，下载文件为："+file.getAbsolutePath());
            path=path+file.getAbsolutePath();
            //解压文件
            String filedir=file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf("."));
            ZipUncompress.unZip(file.getAbsolutePath(),filedir);
            //获取解压目录下的所有文件
            List<File> filelist = FileTool.getFileList(filedir);
            log.info("解压文件共"+filelist.size()+"个json文件");
            if(filelist.size()==0){
                log.info("空包文件，退出任务");
                return true;
            }
            //循环解析所有文件入库
            String fileName=null;
            for (File f :filelist) {
                fileName = f.getName();
                log.info("开始解析"+fileName+"文件");
                String filejsonstr=	FileTool.getjsonStr(filedir+"\\"+fileName);
                //log.info(fileName+"文件内容："+filejsonstr);
                //将json串转对象
                ETCDisputeDetail model=FileTool.parseJsonToObj(filejsonstr, ETCDisputeDetail.class);

                if(model!=null){
                    //文件校验
                    //争议明细记录数
                    int detailCount=0;
                    //争议明细确认总金额
                    long detailAmount=0;
                    List<ETCDisputeDetailMessageList>	msglist= model.getMessageList();;
                    for (int i = 0; i < msglist.size(); i++) {
                        ETCDisputeDetailMessageList msglistModel=msglist.get(i);
                        detailCount+=msglistModel.getTransaction().size();
                        detailAmount+=msglistModel.getAmount();
                    }

                    if(detailCount>model.getCount()){
                        log.info(fileName+"文件内容总记录数和明细记录数不一致");
                        throw	new XJException(sender==Config.issuerId?Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD_ISSUEID:Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD, version, "ETC争议处理结果交易下载请求响应失败："+fileName+"文件内容总记录数和明细记录数不一致"+path, 4);
                    }
                    if(detailAmount!=model.getAmount()){
                        log.info(fileName+"文件内容总确认金额和明细确认金额不一致");
                        throw	new XJException(sender==Config.issuerId?Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD_ISSUEID:Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD, version, "ETC争议处理结果交易下载请求响应失败："+fileName+"文件内容总确认金额和明细确认金额不一致"+path, 4);
                    }



                    //更新交易状态 循环处理每个交易包

                    for (int i = 0; i < msglist.size(); i++) {
                        ETCDisputeDetailMessageList msglistModel=msglist.get(i);
                        List<ETCDisputeDetailTransaction> transList=msglistModel.getTransaction();
                        for (int j = 0; j < transList.size(); j++) {
                            Map map = new HashMap();
                            map.put("messageID", msglistModel.getMessageId());
                            map.put("disputID", transList.get(j).getTransactionId());
                            map.put("result", transList.get(j).getResult());
                            map.put("fileID", model.getDisputedId());
                            map.put("processTime", DateUtil.formatDateTime6(model.getProcessTime()));


                            //检查交易包中信息与系统数据是否一致
                            //交易包号是否存在
                            Integer count=null;
                            Map map2 = new HashMap();
                            map2.put("messageID", msglistModel.getMessageId());
                            map2.put("userID", sender==Config.tollProvinceId?"0":model.getTollProvinceId());
                            map2.put("issueID", sender==Config.issuerId?"6501":TypeTransUtil.issueIDTonetID(model.getIssuerId()));
                            //不再校验完整性
                            //count=(Integer) sqlMapClient.queryForObject("ZfkExitW_ORACLE.checkDisputeIDByIssueID",map2);
                            //修改校验是否已经记账查询
                            count = zfkExitWasteDao.checkDisputeID(map2);
                           // count=(Integer) sqlMapClient.queryForObject("ZfkExitW_ORACLE.checkDisputeID",map2);

                            if(count!=null&& count>0){
                                log.info("交易包号："+msglistModel.getMessageId()+"对应的发行方："+model.getIssuerId()+"服务方"+model.getTollProvinceId()+"未记账，不能处理争议");
                                throw new XJException(sender==Config.issuerId?Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD_ISSUEID:Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD, version, "ETC争议处理结果交易下载请求响应失败：争议文件号："+model.getDisputedId()+"对应的发行方："+model.getIssuerId()+"服务方"+model.getTollProvinceId()+"数量："+model.getCount()+"争议数据不存在或是争议处理,不能处理争议"+path+"--"+fileName, 4);
                            }


                            //发行方争议处理
                            if(sender.equals(Config.issuerId)){
//				    			if(model.getSerProvinceId().equals(model.getTollProvinceId())){
                                if(model.getTollProvinceId().equals(model.getSerProvinceId())||model.getSerProvinceId()==null){//2019-03-27 根据部中心20190322文件修改 wangyp
                                    //根据交易包号和服务方编号修改交易数据 NETID=6501 且UserID!=0
                                    map.put("userID",model.getTollProvinceId());
                                    if(transList.get(j).getResult()==0){
                                        map.put("disputeResult", "3");
                                        //确认
                                        zfkExitWasteDao.IssueIDDisputeTranstionByID(map);
                                        //sqlMapClient.update("ZfkExitW_ORACLE.IssueIDDisputeTranstionByID",map);
                                    }else{
                                        map.put("disputeResult", "10");
                                        //坏账
                                        zfkExitWasteDao.IssueIDDisputeTranstionByHZ(map);
                                        //sqlMapClient.update("ZfkExitW_ORACLE.IssueIDDisputeTranstionByHZ",map);
                                    }
                                    //更新争议流水表
                                    zfkExitWasteDao.EditDisputeWaste(map);
                                  // sqlMapClient.update("ZfkExitW_ORACLE.EditDisputeWaste",map);
                                }else{
                                    log.info("交易包号："+msglistModel.getMessageId()+"服务方"+model.getTollProvinceId()+"通行方："+model.getSerProvinceId()+"争议ID"+model.getDisputedId()+"暂不修改原始交易");
                                }


                            }else if(sender.equals(Config.tollProvinceId)){
                                //根据交易包号和发行方编号修改交易数据 NETID!=6501 且userID=0
                                map.put("issueID",TypeTransUtil.issueIDTonetID(model.getIssuerId()) );
                                zfkExitWasteDao.DisputeTranstionByID(map);
                               // sqlMapClient.update("ZfkExitW_ORACLE.DisputeTranstionByID",map);

                            }
                        }

                    }

                    //Tbl_DataExchangeList插入
                    DataExchangeList dataExchangeList=addDataExchangeList(model);
                    dataExchangeListDao.addDataExchangeList(dataExchangeList);
                    //sqlMapClient.insert("Base_ORACLE.addDataExchangeList",dataExchangeList);
                    //插入日志
                   // DataExchangeLog dataLog = addLog(model,1, "ETC争议交易下载成功");
                   // sqlMapClient.insert("Base_ORACLE.addDataExchangeLog",dataLog);
                    log.info("结束解析"+fileName+"文件");
                }else{
                    log.info("解析"+fileName+"文件转换对象失败");
                    //添加版本异常表
                    throw	new XJException(sender==Config.issuerId?Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD_ISSUEID:Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD, version, "ETC争议处理结果交易下载请求响应失败：解析"+fileName+"文件转换对象失败"+path, 3);
                }
                //删除文件
                f.delete();
            }
            if(type==1){
               // addDownErrorVersion(version, sender==Config.issuerId?Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD_ISSUEID:Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD, "ETC争议处理结果交易下载请求响应成功文件："+file.getAbsolutePath(),0);
                //修改下载版本号
                version=TypeTransUtil.getNextVersion(version, Constants.DOWNLOAD_FILE_1H);
                Map map2 = new HashMap<>();
                map2.put("version", version);
                map2.put("MsgType", sender==Config.issuerId?Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD_ISSUEID:Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD);
                downVersionDicDao.editVersion(map2);
                //sqlMapClient.update("Base_ORACLE.editVersion",map2);
            }

            //删除文件夹
            File F = new  File(filedir);
            F.delete();
            flag=true;
        } catch (IOException e) {
            // TODO: handle exception
            log.info("ETC争议处理结果交易下载请求响应失败,版本号："+version+":"+e.getMessage());
            throw new Exception(new XJException(sender==Config.issuerId?Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD_ISSUEID:Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD, version, "ETC争议处理结果交易下载请求响应失败IO异常,版本号："+version+path+":"+e.getMessage(), 1));
        } catch (ApiRequestException apie) {
            //TODO 系统自定义异常处理，各省补全
            apie.printStackTrace();
            if(apie.getErrCode()==Constants.EMPTYDATACODE){
                log.info("ETC争议结果文件下载请求无数据711,版本号："+version+":正常退出");
                if(type==1){
                    //addDownErrorVersion(version, sender==Config.issuerId?Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD_ISSUEID:Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD, "ETC争议处理结果交易下载请求响应成功无数据",0);
                    //修改下载版本号
                    version=TypeTransUtil.getNextVersion(version, Constants.DOWNLOAD_FILE_1H);
                    Map map2 = new HashMap<>();
                    map2.put("version", version);
                    map2.put("MsgType", sender==Config.issuerId?Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD_ISSUEID:Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD);
                    downVersionDicDao.editVersion(map2);
                    //sqlMapClient.update("Base_ORACLE.editVersion",map2);
                }
                flag=true;

            }else{
                log.error("ETC争议处理结果交易下载请求响应失败,版本号："+version+"错误码："+apie.getErrCode()+" 错误信息："+apie.getMessage());
                throw new Exception(new XJException(sender==Config.issuerId?Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD_ISSUEID:Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD, version, "ETC争议处理结果交易下载请求响应失败错误码："+apie.getErrCode()+path+" 错误信息："+apie.getMessage(), apie.getErrCode()));
            }
        }catch (XJException e) {
            throw new Exception(e);
        }catch (SQLException e) {
            String msg=TypeTransUtil.getErrorMessage(e.getMessage()) ;
            throw new Exception(new XJException(sender==Config.issuerId?Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD_ISSUEID:Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD, version, "ETC争议处理结果文件下载请求响应失败:"+path+msg, 7));
        }catch (Exception e) {
            //添加版本异常表
            String msg=TypeTransUtil.getErrorMessage(e.getMessage()) ;
            throw new Exception(new XJException(sender==Config.issuerId?Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD_ISSUEID:Constants.DOWNLOAD_TYPE_ETCDISPUTEDOWNLOAD, version, "ETC争议处理结果交易下载请求响应失败："+path+msg, 3));
        }



        return flag;

    }
    /**
     * 添加全国联网记录
     * @param
     * @param
     * @return
     * @throws Exception
     */
    public DataExchangeList addDataExchangeList(ETCDisputeDetail model)throws Exception{
        Date nowTime=  new Date();
        DataExchangeList dataExchangeList= new DataExchangeList();
        dataExchangeList.setMessageID(model.getDisputedId().toString());
        dataExchangeList.setSenderID(model.getIssuerId());
        dataExchangeList.setReceiverID(model.getTollProvinceId());
        dataExchangeList.setProcessTime(nowTime);
        dataExchangeList.setMessageClass(2);
        dataExchangeList.setMessageType(5);
        dataExchangeList.setContentType(2);
        dataExchangeList.setResult(1);
        dataExchangeList.setRecCount(model.getCount());
        dataExchangeList.setRecAmount(model.getAmount());
        dataExchangeList.setVersion(0);
        dataExchangeList.setReplyFlag(1);
        dataExchangeList.setReplyTime(nowTime);
        dataExchangeList.setFileName("-");
        dataExchangeList.setResultDesc("ETC争议处理结果下载成功");
        dataExchangeList.setSpare1(model.getDisputedId().toString());
        dataExchangeList.setSpare3("争议处理结果下载");
        return dataExchangeList;

    }
}
